"""
ConnLLM Moonshot提供商V2实现
提供Moonshot API访问和特有功能支持
"""

from typing import Dict, Any, List, Optional
import logging

from ..core_v2.provider import BaseProviderV2
from ..core_v2.processors.tool_call import ToolCallProcessor
from ..core_v2.processors.web_search import WebSearchProcessor

logger = logging.getLogger("connllm.providers.moonshot_v2")

class MoonshotProviderV2(BaseProviderV2):
	"""Moonshot API提供商V2实现"""
	
	# 可用模型常量
	MOONSHOT_V1_8K = 'moonshot-v1-8k'
	MOONSHOT_V1_32K = 'moonshot-v1-32k'
	MOONSHOT_V1_128K = 'moonshot-v1-128k'
	MOONSHOT_V1_AUTO = 'moonshot-v1-auto'
	KIMI_LATEST = 'kimi-latest'
	
	def __init__(self, config: Dict[str, Any]):
		"""
		初始化Moonshot提供商
		
		Args:
			config: 配置字典
		"""
		# 设置提供商类型
		if "provider_type" not in config:
			config["provider_type"] = "moonshot"
			
		# 设置默认base_url（如果配置中没有提供）
		if "base_url" not in config:
			config["base_url"] = "https://api.moonshot.cn/v1"
			
		# 保存特有配置，在调用父类初始化前
		self.search = config.get("search", False)
		self.moonshot_version = config.get("api_version", "v1")
		
		# 调用父类初始化
		super().__init__(config)
	
	def _init_capabilities(self) -> None:
		"""初始化提供商级能力"""
		try:
			# 导入提供商级能力实现
			from ..implementations.moonshot.web_search_v2 import MoonshotWebSearchV2
			
			# 添加网络搜索能力（如果配置中启用）
			if self.search:
				self.capability_manager.register("web_search", MoonshotWebSearchV2)
				logger.debug("已注册Moonshot网络搜索能力")
				
		except ImportError as e:
			logger.warning(f"导入Moonshot提供商级能力实现失败: {str(e)}")
			logger.warning("将创建临时模拟实现以保持功能完整性")
			
			# 创建临时能力实现
			from ..core_v2.capability import Capability
			
			class TempWebSearchCapability(Capability):
				def is_supported(self) -> bool:
					return True
					
				def prepare_request(self, params):
					return params
					
				def detect_search_calls(self, response):
					return []
					
				def execute_search_calls(self, search_calls):
					return []
			
			# 添加临时能力
			if self.search:
				self.capability_manager.register("web_search", TempWebSearchCapability)
				logger.debug("已注册Moonshot临时网络搜索能力")
	
	def _init_model_capabilities(self) -> None:
		"""初始化模型级能力"""
		try:
			# 导入模型级能力实现
			from ..implementations.moonshot.streaming_v2 import MoonshotStreamingV2
			from ..implementations.moonshot.partial_mode_v2 import MoonshotPartialModeV2
			from ..implementations.moonshot.tool_call_v2 import MoonshotToolCallV2
			
			# 添加流式输出能力
			self.model_capability_manager.register("streaming", MoonshotStreamingV2)
			logger.debug("已注册Moonshot流式输出能力")
			
			# 添加部分输出能力
			self.model_capability_manager.register("partial_mode", MoonshotPartialModeV2)
			logger.debug("已注册Moonshot部分输出能力")
			
			# 添加工具调用能力
			self.model_capability_manager.register("tool_calls", MoonshotToolCallV2)
			logger.debug("已注册Moonshot工具调用能力")
			
		except ImportError as e:
			logger.warning(f"导入Moonshot模型级能力实现失败: {str(e)}")
			logger.warning("将创建临时模拟实现以保持功能完整性")
			
			# 创建临时能力实现
			from ..core_v2.capability import ModelCapability
			
			class TempStreamingCapability(ModelCapability):
				def is_supported_for_model(self, model: str) -> bool:
					return True
					
				def stream_response(self, messages):
					response = self.provider._complete_internal(messages)
					content = self.provider._extract_text_from_response(response)
					yield content
			
			class TempPartialModeCapability(ModelCapability):
				def is_supported_for_model(self, model: str) -> bool:
					return True
					
				def continue_from_partial(self, text, messages):
					return self.provider._complete_internal(messages)
			
			class TempToolCallCapability(ModelCapability):
				def is_supported_for_model(self, model: str) -> bool:
					return True
					
				def prepare_request(self, params):
					return params
					
				def detect_tool_calls(self, response):
					return []
					
				def execute_tool_calls(self, tool_calls):
					return []
			
			# 添加临时能力
			self.model_capability_manager.register("streaming", TempStreamingCapability)
			self.model_capability_manager.register("partial_mode", TempPartialModeCapability)
			self.model_capability_manager.register("tool_calls", TempToolCallCapability)
			logger.debug("已注册Moonshot临时模型能力")
	
	def _build_default_processor_pipeline(self, model: str) -> None:
		"""
		构建默认处理器管道
		
		Args:
			model: 模型名称
		"""
		# 添加工具调用处理器（如果模型支持）
		if self.model_capability_manager.model_supports("tool_calls", model):
			tool_capability = self.model_capability_manager.get("tool_calls")
			processor = ToolCallProcessor(tool_capability)
			self.request_processors.append(processor)
			self.response_processors.append(processor)
			logger.debug("已添加Moonshot工具调用处理器")
		
		# 添加网络搜索处理器（如果启用）
		if self.capability_manager.has("web_search"):
			web_search = self.capability_manager.get("web_search")
			processor = WebSearchProcessor(web_search)
			self.request_processors.append(processor)
			logger.debug("已添加Moonshot网络搜索处理器")
	
	def _get_completion_endpoint(self) -> str:
		"""
		获取完成请求的API端点
		
		Returns:
			API端点路径
		"""
		# 由于base_url已经包含了版本("/v1")，这里不需要再加版本前缀
		return "/chat/completions"
	
	def _prepare_request_params(self, messages: List[Dict[str, Any]]) -> Dict[str, Any]:
		"""
		准备API请求参数
		
		Args:
			messages: 消息列表
			
		Returns:
			请求参数字典
		"""
		# 获取完成设置
		completion_settings = self.config_manager.get_completion_settings()
		
		return {
			"model": self.config_manager.get_model(),
			"messages": messages,
			"max_tokens": completion_settings.get("max_tokens", 4096),
			"temperature": completion_settings.get("temperature", 0.7),
			"top_p": completion_settings.get("top_p", 1.0),
			"presence_penalty": completion_settings.get("presence_penalty", 0.0),
			"frequency_penalty": completion_settings.get("frequency_penalty", 0.0),
			"stream": False  # 非流式模式
		}
